<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
</head>

<body>
    <script>
        // 防抖： 可以让代码在一段时间内只执行一次；
        // 简版防抖；前置防抖：先执行代码在防抖；
        /*  var timer = null;
            document.onclik = function() {
                if (!timer) {
                    console.log(111);
                }
                if (itimer) {
                    classTimeout(timer);
                }
                timer = setTimeout(function() {
                    console.log("执行最后一次");
                    timer = null;
                }, 2000);
            }; */

        //后置防抖
        /*  var timer = null;
                document.onclick = function() {
                    if (timer) {
                        clearTimeout(timer);
                    }
                    timer = setTimeout(function() {
                        console.log("执行最后一次");
                        timer = null;
                        console.log(1111);
                    }, 2000);
                }; */
        //通用版
        //防抖函数，前置防抖
        function debounce(fn, delay) {
            var timer = null;
            return function() {
                if (!timer) {
                    fn();
                }
                if (timer) {
                    clearTimeout(timer);
                }
                timer = setTimeout(function() {
                    timer = null;
                }, delay);
            };
        }
        document.onclick = debounce(function() {
            console.log(111111);
        }, 2000);
    </script>
</body>

</html>